<?php

namespace App\Http\Controllers;

use App\Models\Todolsit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class MainController extends Controller
{
    public function index()
    {
        $todolist = Todolsit::all();
        return view('index', compact('todolist'));
    }

    public function create()
    {
        return view('create');
    }

    public function edit($id)
    {
        $todolist = Todolsit::find($id);

        return view('edit', compact('todolist'));
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'desc' => 'required',
        ], [
            'desc.required' => '任务描述必须填写',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withInput()->withErrors($validator->messages()->first());
        }

        if ($request->has('id')) {
            $todolist = Todolsit::find($request->input('id'));
            $todolist->desc = $request->input('desc');
            $todolist->url = $request->input('url');
            $todolist->save();
        } else {
            $todolist = Todolsit::create($request->all());
        }

        if ($todolist) {
            return redirect()->to(route('todolist.index'));
        }
    }

    public function ok($id)
    {
        $todolist = Todolsit::find($id);

        if ($todolist) {
            $todolist->status = 1;
            $bool = $todolist->save();
            if ($bool) {
                return redirect()->to(route('todolist.index'));
            }
        }

        return redirect()->back();
    }

    public function undid($id)
    {
        $todolist = Todolsit::find($id);

        if ($todolist) {
            $todolist->status = 0;
            $bool = $todolist->save();
            if ($bool) {
                return redirect()->to(route('todolist.index'));
            }
        }

        return redirect()->back();
    }
}
